package com.szholly.pro.watergas_server.ps.android.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.android.bean.QcTaskParam;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.NonNullUtil;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.SqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.TableRowMap;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.controller.QcService;
import com.szholly.pro.watergas_server.ps.data.QcWaterThanRow;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONObject;

public class QcTaskDataContrastStrategy extends QcTaskStrategy {
	QcService mDomainManager = QcService.get();
	
	public QcTaskDataContrastStrategy(QcOperationService mOperationService) {
		super(mOperationService);
	}
	
	@Override
	public List<RowBase> getTaskList(QcTaskParam taskParam) throws Exception {		
		return mOperationService.getOperationTaskList(taskParam);
	}

	@Override
	public RowBase addTask(QcTaskParam taskParam) throws Exception {
		return mOperationService.addOperationTask(taskParam);
	}

	@Override
	public void deleteTask(QcTaskParam taskParam) throws Exception {
		mOperationService.deleteOperationTask(taskParam);
	}

	private void executeDeleteTaskContent(String taskCode) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "delete from QC_WATER_THAN t\n" + " where t.THANTYPE = '0'\n" + "   and t.operation_task_code = @taskCode";
		DataUtil.ExecuteUpdateSql(sql, parms);
	}

	@Override
	public void deleteProcessedTask(QcTaskParam taskParam) throws Exception {
		String userId = taskParam.getUserId();
		String taskCode = taskParam.getTaskCode();		
		
		SecurityConfig config = SecurityConfig.get(userId);
		ValidUtils.isTrue(config.containQcDeleteProcessedTask,"权限不够");
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			mOperationService.deleteOperationTask(taskParam);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}		
	}
	
	@Override
	public RowBase getProcessedTaskInitData(QcTaskParam taskParam) throws Exception {
		String taskCode = taskParam.getTaskCode();
		String companyCode = taskParam.getCompanyCode();
		List<RowBase> valueList = getValueList(taskCode);
		ValidUtils.notEmpty(valueList, "数据异常(比对详情为空)");
		Map<String, Map<String, String>> valueMap = new HashMap<String, Map<String, String>>();// <参数编号，一条>
		for (RowBase rowBase : valueList) {
			Map<String, String> beanMap = new HashMap<>();
			beanMap.put("value", rowBase.getSafeString(QcWaterThanRow.FIELD_Value));
			beanMap.put("onLineValue", rowBase.getSafeString(QcWaterThanRow.FIELD_Rtd));
			valueMap.put(rowBase.getSafeString(QcWaterThanRow.FIELD_Parmname), beanMap);
		}
		String dateTime = valueList.get(0).getSafeString("datetime");
		List<RowBase> parameterList =  mParameterService.getLabParameterList(companyCode);
		RowBase resultMap = new RowBase();
		resultMap.put("parameterList", NonNullUtil.toList(parameterList));
		resultMap.put("valueMap", valueMap);
		resultMap.put("dateTime", dateTime);
		return resultMap;
	}

	@Override
	public RowBase getTaskInitData(QcTaskParam taskParam) throws Exception {
		String companyCode = taskParam.getCompanyCode();
		List<RowBase> parameterList = mParameterService.getLabParameterList(companyCode);
		if (CollectionUtils.isEmpty(parameterList)) {
			throw new Exception("没有比对参数");
		}
		RowBase resultMap = new RowBase();
		resultMap.put("parameterList", parameterList);
		resultMap.put("dateTime", new DateTime().toString());
		return resultMap;
	}

	@Override
	public void saveTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		JSONObject dataObject = JSONObject.fromObject(data);
		List<TableRowMap> list = TableRowMap.get(dataObject.getJSONArray("valueList"), "QC_WATER_THAN");
		ValidUtils.notEmpty(list, "数据不能为空");

		JSONObject taskJson = dataObject.getJSONObject("taskBean");
		String TASK_CODE = taskJson.optString("TASK_CODE");
		String TASK_DESC = taskJson.optString("TASK_DESC");

		try {
			DataUtil.beginTransaction();
			SqlUtils.prepareInsert(list);
			preFinishOperationTask(TASK_CODE, TASK_DESC);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	@Override
	public void updateTask(QcTaskParam taskParam) throws Exception {
		String data = taskParam.getData();
		String taskCode = taskParam.getTaskCode();		
		ValidUtils.hasText(taskCode, "运维任务编号为空,数据编辑失败");
		JSONObject dataObject = JSONObject.fromObject(data);
		List<TableRowMap> list = TableRowMap.get(dataObject.getJSONArray("valueList"), "QC_WATER_THAN");
		ValidUtils.notEmpty(list, "数据不能为空");
		JSONObject taskJson = dataObject.getJSONObject("taskBean");
		String TASK_CODE = taskJson.optString("TASK_CODE");
		String TASK_DESC = taskJson.optString("TASK_DESC");
		
		try {
			DataUtil.beginTransaction();
			executeDeleteTaskContent(taskCode);
			SqlUtils.prepareInsert(list);
			preFinishOperationTask(TASK_CODE, TASK_DESC);
			DataUtil.commitTransaction();
		} catch (Exception e) {
			DataUtil.rollbackTransaction();
			throw e;
		}
	}

	private List<RowBase> getValueList(String taskCode) throws Exception {
		ValidUtils.hasText(taskCode, "运维任务编号为空,数据获取失败");
		List<GlobalParameter> parms = new ArrayList<>();
		parms.add(new GlobalParameter("taskCode", taskCode));
		String sql = "select t.parmname,\n"
				+ "       t.rtd,\n"
				+ "       t.value,\n"
				+ "       to_char(t.datetime, 'yyyy-mm-dd hh24:mi:ss') datetime\n"
				+ "  from QC_WATER_THAN t\n"
				+ " where t.operation_task_code = @taskCode";
		return DataUtil.getSelectRows(sql, parms);
	}

}
